package com.zhaoyang.dao;

import com.zhaoyang.model.Clazz;
import com.zhaoyang.model.Page;
import com.zhaoyang.util.StringUtil;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 赵扬
 * @time 2020/4/27 17:48
 */
public class ClazzDao extends BaseDao {

    /**
     * 添加班级
     *
     * @param clazz
     * @return
     */
    public boolean addClazz(Clazz clazz) {
        String sql = "insert into s_clazz values(?,?,?)";
        int cnt = template.update(sql, clazz.getId(), clazz.getName(), clazz.getInfo());
        return cnt == 1;
    }

    /**
     * 删除班级
     *
     * @param id
     * @return
     */
    public boolean deleteClazz(int id) {
        String sql = "delete from s_clazz where id = ?";
        int cnt = template.update(sql, id);
        return cnt == 1;
    }

    /**
     * 修改班级信息
     *
     * @param clazz
     * @return
     */
    public boolean editClazz(Clazz clazz) {
        String sql = "update s_clazz set name = ? ,info = ? where id = ?";
        int cnt = template.update(sql, clazz.getName(), clazz.getInfo(), clazz.getId());
        return cnt == 1;
    }

    /**
     * 获取班级列表
     *
     * @param clazz
     * @param page
     * @return
     */
    public List<Clazz> getClazzList(Clazz clazz, Page page) {
        List<Clazz> ret = new ArrayList<Clazz>();
        String sql = "select * from s_clazz ";
        if (!StringUtil.isEmpty(clazz.getName())) {
            sql += "where name like '%" + clazz.getName() + "%'";
        }
        sql += " limit " + page.getStart() + "," + page.getPageSize();
        ResultSet resultSet = query(sql);
        try {
            while (resultSet.next()) {
                Clazz cl = new Clazz();
                cl.setId(resultSet.getInt("id"));
                cl.setName(resultSet.getString("name"));
                cl.setInfo(resultSet.getString("info"));
                ret.add(cl);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * 获取班级数
     *
     * @param clazz
     * @return
     */
    public int getClazzListTotal(Clazz clazz) {
        int total = 0;
        String sql = "select count(*)as total from s_clazz ";
        if (!StringUtil.isEmpty(clazz.getName())) {
            sql += "where name like '%" + clazz.getName() + "%'";
        }
        ResultSet resultSet = query(sql);
        try {
            while (resultSet.next()) {
                total = resultSet.getInt("total");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return total;
    }
}
